// import { json } from 'express'
import Vue from 'vue'
import Vuex from 'vuex'
import router from '@/router'

Vue.use(Vuex)

const storePersist = (store) => {
  const storage = window.sessionStorage // 存储对象
  const key = "MyVuexStorePersist" // 存储的键

  const data = storage.getItem(key)
  data && store.replaceState(JSON.parse(data))

  // 当store 初始化后调用
  store.subscribe((mutation, state) => {
    // 每次mutation 之后调用
    // mutation 的格式为{type,payload}
    storage.setItem(key, JSON.stringify(state))
  })
}

export default new Vuex.Store({
  state: {
    // 用户信息
    user: {},

    /** 
    *菜单列表
    */
    menus: []
  },
  mutations: {

    setUser(state, payload) {
      state.user = payload
    },

    /** 
    *设置菜单
    */
    setMenus(state, payload) {
      state.menus = payload
    }
  },
  actions: {
    /** 
     * 退出
    */
    exit({ commit }) {
      commit("setUser", {});
      commit("setMenus", []);
      router.push({ name: "login" })
    }
  },
  modules: {
  },
  getters: {
    /**
    * token
    */
    token(state) {
      return state.user.token
    }
  },
  plugins: [storePersist]
})
